package routers

import (
	"fmt"
	"gin-blog/handlers"
	"gin-blog/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	}
}
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("中间件开始执行---start")
		tokenString := c.Request.Header.Get("token")
		fmt.Println("获取到token参数为：", tokenString)
		if tokenString == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "token为空",
			})
			c.Abort()
		}
		getToken, err := pkg.GetToken(tokenString)
		if err != "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "token验证失败",
			})
			c.Abort()
		}
		fmt.Println("解析完token参数后：", getToken)
		c.Set("uid", getToken["uid"])

		fmt.Println("中间件执行完毕---end")
		c.Next()
	}
}
func Init() *gin.Engine {
	r := gin.Default()
	// 2.绑定路由规则，执行的函数
	// gin.Context，封装了request和response
	r.Use(Cors())

	r.POST("/users/login", handlers.UsersLogin)
	r.GET("users/list", handlers.UsersList)
	r.GET("/users/detail", handlers.UsersDetail)

	r.Static("static", "./static")
	r.GET("/list", handlers.List)
	r.POST("/add", handlers.Add)
	r.GET("/del", handlers.Del)
	r.GET("/det", handlers.Det)
	r.POST("/user/login", handlers.UserLogin)
	r.GET("/user/login/gettoken", MiddleWare(), handlers.UserGetToken)
	return r
	// 3.监听端口，默认在8080
	// Run("里面不指定端口号默认为8080")
	//r.Run(":8000")
}
